package com.gage.controller.admin;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gage.controller.base.BaseController;
import com.gage.commons.result.PageInfo;
import com.gage.model.shiro.ShiroUser;
import com.gage.commons.utils.JsonUtils;
import com.gage.commons.utils.StringUtils;
import com.gage.model.SysBaseDict;
import com.gage.service.ISysDictService;

@Controller
@RequestMapping({ "/dict" })
public class SysBaseDictController extends BaseController
{
	@Autowired
	private ISysDictService sysDictService;
/**
 * 数据字典页面
 * @author lkr
 * @param request
 * @param model
 * @date:20170512
 * @return
 */
	@RequestMapping("/index")
	public String index(HttpServletRequest request, Model model)
	{
		return "/admin/dicts/index";
	}
/**
 * 加载树
 * @author lkr
 * @date:20170512
 * @param request
 * @param id
 * @return
 */
	@PostMapping("/tree")
    @ResponseBody
	public Object getDictsTree(HttpServletRequest request,String id)
	{
		if (StringUtils.isEmpty(id))
		{
			id = "sjzd";
		}
		return sysDictService.selectDictsTree(id);
	}
	 /**
     * 数据字典列表
     * @author lkr
     * @date:20170512
     * @param userVo
     * @param page
     * @param rows
     * @param sort
     * @param order
     * @return
     * @return
     */
    @PostMapping("/dataGrid")
    @ResponseBody
    public Object dataGrid(SysBaseDict dict, Integer page, Integer rows, String sort, String order) {
        PageInfo pageInfo = new PageInfo(page, rows, sort, order);
        Map<String, Object> condition = new HashMap<String, Object>();
        System.out.println("*****pid********"+dict.getParentid());
        if (StringUtils.isNotEmpty(dict.getDictname())) {
            condition.put("dictname", dict.getDictname());
        }
        if (StringUtils.isNotEmpty(dict.getParentid())) {
            condition.put("parentid", dict.getParentid());
        }else {
        	 condition.put("parentid", "0");
		}
        pageInfo.setCondition(condition);
        return sysDictService.selectDataGrid(pageInfo);
    }
    /**
     * 添加数据字典页
      * @author lkr
      * @date:20170512
     * @return
     */
    @GetMapping("/add")
    public String addPage(Model model) {
        return "admin/dicts/edit";
    }
    /**
     * 编辑数据字典页
     *
     * @return
     */
    @GetMapping("/edit")
    public String editPage(String id,Model model) {
    	SysBaseDict dict=null;
    	if (StringUtils.isNotEmpty(id)) {
    		dict=	sysDictService.getDictById(id);
    		String parentId=dict.getParentid();
    		if (StringUtils.isEmpty(parentId)) {
    			dict.setParentid("0");
			}
		}
    	model.addAttribute("dict", dict);
        return "admin/dicts/edit";
    }
    /**
     * @author lkr
     * @date:20170512
     * @param dict
     * @param result
     * @return
     */
    @PostMapping("/save")
    @ResponseBody
	public Object save(@Valid SysBaseDict dict,String oldId,String oldCode, BindingResult result)
	{
    	boolean status=false;
		ShiroUser u = this.getShiroUser();
		SysBaseDict dicts = sysDictService.getDictByDictcode(dict.getDictcode());
			if (StringUtils.isEmpty(dict.getId()))
			{
				if (StringUtils.isEmpty(dicts))
				{	
					if (StringUtils.isEmpty(dict.getParentid())) {
						dict.setDictlevel(1);
						dict.setParentid("0");
					}
					dict.setId(StringUtils.getUUId());
					dict.setInsertid(u.getId().toString());
					dict.setUpdateDate(new Date());
					dict.setInsertDate(new Date());
					status=sysDictService.insert(dict);
				} else
				{
					return resultJson("0","字典编码已存在！","");
				}
			} else
			{
				if (StringUtils.isNotEmpty(dicts)) {
					String pId=dicts.getId().toString();
					if (!oldId.equals(pId)) {
						return resultJson("0","字典编码已存在！","");
					}
				}
				dict.setUpdateDate(new Date());
				dict.setUpdateid(u.getId().toString());
				status=sysDictService.updateById(dict);
				List<SysBaseDict> dictList=sysDictService.findDictByPid(oldCode);
				if (dictList.size()>0) {
					for (SysBaseDict pDict:dictList) {
						pDict.setParentid(dict.getDictcode());
						status=sysDictService.updateById(pDict);
					}
				}
			}
			return resultJson("1","信息保存成功","");
	}
    /**
     * 删除字典
     * @author lkr
 	 * @date:20170512
     * @param id
     * @return
     */
    @PostMapping("/delete")
    @ResponseBody
    public Object delete(String id) {
    	int count=0;
    	String[] ids = id.split(",");
    	List<String> list = new ArrayList<String>();
		for (int i = 0; i < ids.length; i++){
			count=sysDictService.getCountChild(ids[i]);
	    	if (count>0) {
	    		SysBaseDict dict=sysDictService.getDictById(ids[i]);
	    		return renderSuccess("该"+dict.getDictname()+"栏目存在子栏目，不能删除！");
			}else {
				list.add(ids[i].trim());
			}
		}
		
		if (this.sysDictService.removeDict(list))
		{
			return renderSuccess("成功删除"+ids.length+"条信息！");
		} else
		{
			return renderError("删除失败，删除操作出错！");
		}
       // sysDictService.deleteUserById(id);
    }
    /**移动树
     * @author lkr
     * @date:20170512
     * @param dictcode
     * @param parentid
     * @return
     */
    @PostMapping("/move")
    @ResponseBody 
	public Object move(String dictcode,String parentid){		
		if (StringUtils.isNotEmpty(dictcode)&&StringUtils.isNotEmpty(parentid)){
			int n=sysDictService.updateMoveDict(dictcode,parentid);
			if (n==0){
				return renderSuccess("移动失败！");
			}
			return renderSuccess("移动成功！");
		}else {
			return renderSuccess("网络异常！");
		}
	}
	/**
	 * 获取数据字典通用方法
	 * 
	 */
    @GetMapping("/getComboxDictByPid")
    @ResponseBody
    public Object getComboxDictByPid(Model model,String pid) {
    	if (StringUtils.isNotEmpty(pid)) {
    		pid="";
		}
    	List<SysBaseDict> dictList=sysDictService.findDictByPid(pid);
    	String listJson=JsonUtils.javaList2JsonList(dictList);
    	model.addAttribute("dictList", dictList);
		return listJson;
	}
}
